<?php

/**
 * Classe para sistema de login e senha
 * com autenticacao e validação de usuarios
 *
 * @author Robert Diego de Jesus <beto.corujao@gmail.com>
 * @version 0.1
 * @package userAutentic.class
 * @subpackage userAutentic
 * @access public
 */

require("connectMysql.class.php");

class userAuthentic extends connectMysql{


    /**
     * Metodo de validacao de acesso a um sistema
     * Este metodo permite a validacao com ate 4 parametros:
     * <p>usuario, senha, atividade e bloqueio </p>
     * @name accessValidation
     * @access public
     * @return void
     *
     * @param string $tabela Nome da tabela onde estao os dados para validacao
     * @param string $page_success Endereco da pagina caso o login esteja correto
     * @param string $page_fail Endereco da pagina caso o login esteja errado
     * @param array $array_validation Array contendo o campo a ser acessado no BD e o valor valido
     *          <p> O array deve ser criado na ordem: usuario, senha, atividade e bloqueio <p>
     *          <p> array( <b>'nome'</b> => $username, <b>'senha'</b> => $pass, <b>'active'</b> => 'Ativo',
     *              <b>'block'</b> =>'Desblo' ) </p>
     *          <p> Onde os <b>indices</b> sao os campos do BD, $username e $pass sao recebidos do formulario , </p>
     *          <p> <b>atividade</b> deve-se informar qual o valor indica se o usuarios esta ativo e em <b>bloqueio</b> </p>
     *          <p>  deve-se informar o valor que indica que o usuario esta desbloqueado. </p>
     *          <br />
     *          <p> <b>Obs:Atividade e Bloqueio devem ser omitidas caso nao estejam no banco de dados.</b> </p>
     */

     public function accessValidation($table,$page_success,$page_fail,$array_validation){

//             $array_validation = array(  //campo BD   => //valor valido
//                                          'matricula' => $username,
//                                          'senha'     => $password,
//                                          'atividade' => 'Ativo',
//                                          'bloqueio'  => 'Desbloqueado'
//                                      );


        $keys = array_keys($array_validation);

        $username = $array_validation[$keys[0]];

           $sql = $this->select("SELECT * FROM $table WHERE  $keys[0] = '$username' ");
           $cont = mysql_num_rows($sql); // verifica se existe um registro com aquele login

            while($line = mysql_fetch_array($sql)){ //busca a senha do login
                    $password_db = $line[$keys[1]];
                    $atividade = $line[$keys[2]];
                }//fim_while

                if($array_validation[$keys[0]] == NULL){                  
                     header("Location: ".$page_fail."?access=user_empty");
                }
                else if($array_validation[$keys[1]] == NULL){
                              header("Location: ".$page_fail."?access=pass_empty");
                }
                else if($cont == 0){
                              header("Location: ".$page_fail."?access=user_error");
                }
                else if(isset($password_db) != $array_validation[$keys[1]]) { // se nao existir senha igual no db
                              header("Location: ".$page_fail."?access=pass_error");
                }
                else if(count($array_validation)>= 3 && @$atividade != $array_validation[$keys[2]]){
                              header("Location: ".$page_fail."?access=activity_error");
                }
                else {
                        session_start();
                        $_SESSION['login'] = $username;
                        $_SESSION['password'] = $array_validation[$keys[1]];
                        header("Location: ".$page_success);
               }

     }


     public function userValidation($table, $username, $username_field, $password, $pass_field, $page_success,
                                    $page_fail, $activity_field=NULL, $if_activity=NULL){

           $sql = $this->select("SELECT * FROM $table WHERE $username_field = '$username' ");
           $cont = mysql_num_rows($sql); // verifica se existe um registro com aquele login

            while($line = mysql_fetch_array($sql)){ //busca a senha do login

                    $password_db = $line[$pass_field];
                    $atividade = $line[$activity_field];

                }//fim_while


                if($username == NULL){
                              header("Location: ".$page_fail."?access=user_empty");
                }
                else if($password == NULL){
                              header("Location: ".$page_fail."?access=pass_empty");
                }
                else if($cont == 0){
                              header("Location: ".$page_fail."?access=user_error");
                }
                else if(isset($password_db) != $password) { // se nao existir senha igual no db
                              header("Location: ".$page_fail."?access=pass_error");
                }
                else if(@$atividade != $if_activity){
                              header("Location: ".$page_fail."?access=activity_error");
                }
                else {
                        session_start();
                        $_SESSION['login'] = $username;
                        $_SESSION['password'] = $password;
                        header("Location: ".$page_success);
               }

        }


     public function userAuthentication($username_table, $table, $pageFail){
            session_start();

            if(isset($_SESSION["login"]) AND isset($_SESSION['password'])) {


                     $login_usuario = $_SESSION["login"];
                     $senha_usuario = $_SESSION["password"];

            $sql = $this->select("SELECT * FROM $table WHERE $username_table = '$login_usuario' ");
                    $cont = mysql_num_rows($sql);

                    while($linha = mysql_fetch_array($sql)){
                                    $senha_db = $linha['senha'];
                    }//fim_while

                    if($cont == 0) { // se nao existir login igual no db

                            unset($_SESSION["login"]);
                            unset($_SESSION["password"]);

                            header("Location: ".$pageFail."?access=user_error");
                    }//fim_if
                    else if($senha_db != $senha_usuario){

                            unset($_SESSION["login"]);
                            unset($_SESSION["password"]);

                            header("Location: ".$pageFail."?access=pass_error");

                    }//fim_if

            } //fim_if
            else{
                            header("Location: ".$pageFail."?access=error");

                    } // fim_else


        }


     public function userLevelAuthentication($table, $username_field, $level_field, $page_level, $page_success, $page_fail ){
             session_start();

            if(isset($_SESSION["login"]) AND isset($_SESSION['password'])) {


                     $login_user = $_SESSION["login"];
                     $pass_user  = $_SESSION["password"];

            $sql = $this->select("SELECT * FROM $table WHERE $username_field = '$login_user' ");
                    $cont = mysql_num_rows($sql);

                    while($linha = mysql_fetch_array($sql)){
                                    $senha_db = $linha['senha'];
                                    $level_db = $linha[$level_field];
                    }//fim_while

                    if($cont == 0) { // se nao existir login igual no db

                            unset($_SESSION["login"]);
                            unset($_SESSION["password"]);

                            header("Location: ".$page_fail."?access=user_error");
                    }//fim_if
                    else if($senha_db != $pass_user){

                            unset($_SESSION["login"]);
                            unset($_SESSION["password"]);

                             header("Location: ".$page_fail."?access=pass_error");
                    }//fim_if
                    if($level_db != $page_level){

                         header("Location: ".$page_success."?access=level_error");
                }//fim_if

            } //fim_if
            else{
                             header("Location: ".$page_fail."?access=error");

                    } // fim_else



        }


     public function userLogout($pageFail){
        session_cache_expire(1);
        session_start();

                        unset($_SESSION["login"]);
                        unset($_SESSION["password"]);

        header("location: ".$pageFail);
        print("<script>location.href='$pageFail';</script>");
    }
     
}

?>